// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    displayCurrentDate();
    loadTasks();
});

// 显示当前日期
function displayCurrentDate() {
    const dateElement = document.getElementById('currentDate');
    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    const today = new Date().toLocaleDateString('zh-CN', options);
    dateElement.textContent = today;
}

// 添加新日程
function addTask() {
    const taskInput = document.getElementById('taskInput');
    const timeInput = document.getElementById('timeInput');
    const taskText = taskInput.value.trim();
    const taskTime = timeInput.value;
    
    if (taskText === '' || taskTime === '') {
        alert('请填写日程内容和时间');
        return;
    }
    
    const task = {
        id: Date.now(),
        text: taskText,
        time: taskTime
    };
    
    saveTask(task);
    renderTask(task);
    
    // 清空输入框
    taskInput.value = '';
    timeInput.value = '';
    taskInput.focus();
}

// 保存日程到本地存储
function saveTask(task) {
    let tasks = getTasks();
    tasks.push(task);
    localStorage.setItem('scheduleTasks', JSON.stringify(tasks));
}

// 从本地存储获取所有日程
function getTasks() {
    return JSON.parse(localStorage.getItem('scheduleTasks')) || [];
}

// 加载所有日程
function loadTasks() {
    const tasks = getTasks();
    tasks.forEach(task => renderTask(task));
}

// 渲染单个日程到页面
function renderTask(task) {
    const taskList = document.getElementById('taskList');
    
    const taskItem = document.createElement('div');
    taskItem.className = 'task-item';
    taskItem.dataset.id = task.id;
    
    taskItem.innerHTML = `
        <div class="task-info">
            <span class="task-time">${formatTime(task.time)}</span>
            <span class="task-text">${task.text}</span>
        </div>
        <button class="delete-btn" onclick="deleteTask(${task.id})">删除</button>
    `;
    
    taskList.appendChild(taskItem);
}

// 格式化时间显示
function formatTime(timeString) {
    const [hours, minutes] = timeString.split(':');
    return `${hours}:${minutes}`;
}

// 删除日程
function deleteTask(id) {
    let tasks = getTasks();
    tasks = tasks.filter(task => task.id !== id);
    localStorage.setItem('scheduleTasks', JSON.stringify(tasks));
    
    // 从DOM中移除
    const taskItem = document.querySelector(`.task-item[data-id="${id}"]`);
    if (taskItem) {
        taskItem.remove();
    }
}